package com.lay.shiro;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lay.entity.Role;
import com.lay.entity.UserNumber;
import com.lay.service.*;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class CustomerRealm extends AuthorizingRealm {
    @Autowired
    private UserNumberService userNumberService;
    @Autowired
    private RoleService roleService;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("=================执行授权======================");

        //返回值 ：AuthorizationInfo ，封装指定用户对应的所有角色，SimpleAuthenticationInfo
        //参数：principalCollection ，登录的身份，用户名。
        SimpleAuthorizationInfo info = null;
        String username = principalCollection.toString();
        //3.查询数据库，是否存在指定用户名
        QueryWrapper qw = new QueryWrapper();
        qw.eq("username",username);
        UserNumber userNumber = userNumberService.getOne(qw);
        //4.如果查到了，封装查询结果【角色的集合】，返回调用
        if(null!=userNumber.getUsername()){
            Set<String> roles = new HashSet<String>();
            Role role = roleService.getById(userNumber.getrId());
            String powers = role.getPowers();
            String[] power = powers.split(",");
            for (String str:power) {
                roles.add(str);
            }
            info = new SimpleAuthorizationInfo(roles);
        }else {
            //5.如果没有查到，抛出异常
            throw new AuthenticationException();
        }
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
       SimpleAuthenticationInfo info;
        System.out.println("=================执行认证======================");
        //1.将token转换成 UsernamePasswordToken
        UsernamePasswordToken uToken = (UsernamePasswordToken) authenticationToken;
        //获取当前用户的姓名
        String username = uToken.getUsername();
        String password = String.valueOf(uToken.getPassword());
        QueryWrapper qw = new QueryWrapper();
        qw.eq("username",username);
        qw.eq("password",password);
        qw.eq("un_state",1);
        UserNumber userNumber = userNumberService.getOne(qw);
        if (userNumber.getUsername() != null){
            info =new SimpleAuthenticationInfo(userNumber.getUsername(),userNumber.getPassword(),this.getName());
        }else {
            throw new AuthenticationException();

        }
        return info;
    }
}
